React Context
✒️ 2025-05-28 10:39 내용 수정
React Component 트리 안에서 전역적이라 볼 수 있는 데이터를 공유하기 위한 방법
- 참고 자료 : React Context
- 공식 사이트 예시로 Context를 사용할만한 데이터는 현재 로그인 한 유저의 정보, 테마, 선호하는 언어 등이 있다.
- 부모 Component로부터 자식 Component로 단계마다 일일이 props를 전달하기에 번거로울 때 어플리케이션 전체의 Component가 사용해야 하는 props가 있을 경우 Context를 사용할 수 있다 .
- props drilling : 반복적인 props를 전달하는 현상
- 여러 단계에 연결된 Component에 공통된 데이터를 전달할 때 사용할 수 있지만, Context 사용시 Component 재사용이 어렵기에 필요할 때만 사용하는 것이 좋다.
- Component 합성을 사용하는 것이 더 간단할 수도 있다.
{props.children}으로 Component에서 자식 요소를 그대로 출력하여 전달할 수 있다.- 참고 자료 : React context를 사용하기 전에 고려할 것
- Component 합성을 사용하는 것이 더 간단할 수도 있다.
- Context.Provider : Context를 하위 Component에 전달하고, Context를 사용할 Component에 Context의 변화를 알린다.
- Provider 하위의 Context를 사용하는 모든 Component는 Provider의 value prop이 바뀔 때마다 다시 렌더링되며, 이러한 방식때문에 객체를 value로 보내는 경우에는 주의해야 한다.
- 이를 피하기 위해 Provider의 value를 부모의 state로 끌어올리는 방법을 사용할 수 있다.
- 참고 자료 : React 주의사항
import { createContext } from "react";
function App() {
// Context 생성하기
const CustomContext = createContext(defaultValue); // defaultValue : 트리 내에 적절한 Provider가 없을 때 사용
return (
// Provider로 Context를 사용할 Component의 범위를 지정할 수 있음
<CustomContext.Provider value={/*사용할 값*/}>
{/* Context를 사용할 Component를 추가 */}
<Test></Test>
</CustomContext.Provider>
)
}
- Context를 JS 파일에서 만들어 export할 수도 있다.
import { createContext } from "react";
const CustomContext = createContext();
export default CustomContext;
import { useState, useContext } from 'react';
import CustomContext from '../contexts/CustomContext';
function App() {
return (
const [custom, setCustom] = useState('test');
{/* custom을 Test에서도 사용할 수 있다. */}
<CustomContext.Provider value={custom}>
{/* Context를 사용할 Component를 추가 */}
<Test></Test>
</CustomContext.Provider>
)
}
- Context를 사용할 자식 Component에서는
useContext()를 사용하여 Context를 사용할 수 있다.
import { useState, useContext } from 'react';
import CustomContext from '../contexts/CustomContext';
function Test() {
{/* Provider로부터 받은 Context 가져와서 변수에 저장 */}
const contextValue = useContext(CustomContext);
return(
<span>{contextValue}</span>
)
}
Context를 개별 함수로 관리하기
- Context, useContext, Provider를 미리 파일에 저장하여 모듈화 시키면 Context를 사용할 자식 Component에선 Provider만 사용할 수 있어 더 간결하게 코드를 작성할 수 있다.
- 아래에선 useContext Hook도 작성 및 export하여 상황에 따라 Provider와 value를 따로 설정할 수 있도록 작성했다.
// TestContext.js
import React, { createContext, useContext, useState } from "react";
const TestContext = createContext();
export function useTest() {
return useContext(TestContext);
}
export function TestProvider({ children }) {
const [testValue, setTestValue] = useState('');
return (
<TestContext.Provider value={{ testValue, setTestValue }}>
{children}
</TestContext.Provider>
);
}
export default TestContext;
// App.js
import { TestProvider } from "./TestContext.js";
import ChildComponent from "./ChildComponent.js";
function App() {
return (
<TestProvider>
<ChildComponent />
</TestProvider>
);
}
export default App;
- 자식 Component에선
useContextHook을 사용하는useTestHook으로 Context의 value를 가져올 수 있다.
// ChildComponent.js
import { useTest } from "./TestContext.js";
function ChildComponent() {
// Context로 전달한 value를 꺼내올 수 있다.
const {testValue, setTestValue} = useTest();
return (
<></>
);
}
export default ChildComponent;